import 'dart:math';

import 'package:dashboard/dio/dio_gateway.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class Cluster extends StatefulWidget {
  const Cluster({super.key});

  @override
  State<Cluster> createState() => _ClusterState();
}

class _ClusterState extends State<Cluster> {
  late List<String> data = [];

  Future loadAsync() async {
    var result = await GateWayDio.GetCluserList();

    var dy = result["cluster_list"] as List<dynamic>;

    data = dy.map((e) => e.toString()).toList();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: loadAsync(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('${snapshot.error}}'));
        } else {
          return Container(
            padding: const EdgeInsets.all(10),
            height: 500,
            child: ListView(
              children: [
                Wrap(
                  children: [
                    ...List.generate(
                        data.length,
                        (index) => ClusterPanel(
                              index: index + 1,
                              servername: data[index],
                            ))
                  ],
                ),
              ],
            ),
          );
        }
      },
    );
  }
}

class ClusterPanel extends StatefulWidget {
  const ClusterPanel(
      {super.key, required this.index, required this.servername});
  final int index;
  final String servername;
  @override
  State<ClusterPanel> createState() => _ClusterPanelState();
}

class _ClusterPanelState extends State<ClusterPanel> {
  late Map<String, dynamic> data = {};

  late int onlines = 0;

  Future loadAsync() async {
    data = await GateWayDio.GetClusterInfo(widget.servername);
    onlines = await GateWayDio.GetChannelsCount(widget.servername);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: loadAsync(),
        builder: (builder, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Card(
              color: Colors.white,
              elevation: 1,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
              margin: const EdgeInsets.all(10),
              child: Container(
                  width: 450,
                  height: 400,
                  padding: const EdgeInsets.all(10),
                  child: const Center(child: CircularProgressIndicator())),
            );
          } else if (snapshot.hasError) {
            return Center(child: Text('${snapshot.error}}'));
          } else {
            return Card(
              color: Colors.white,
              elevation: 1,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
              margin: const EdgeInsets.all(10),
              child: Container(
                  width: 450,
                  padding: const EdgeInsets.all(10),
                  child: Column(children: [
                    ListTile(
                      leading: SizedBox(
                        width: 50,
                        height: 50,
                        child: Container(
                          decoration: BoxDecoration(
                            color: const Color.fromARGB(255, 102, 101, 101),
                            borderRadius: BorderRadius.circular(25),
                          ),
                          child: Center(
                            child: Text(
                              '${widget.index}',
                              style: const TextStyle(color: Colors.white),
                            ),
                          ),
                        ),
                      ),
                      title: Text(
                          '集群名称:${widget.servername.replaceAll("go.micro.api.socket.server.", "")}'),
                      subtitle: Text(
                          'CPU: ${data["cpu"] ?? 0} 已用:${BytesToMBOnMemory(data["heapInuse"])}MB 在线:$onlines \nCPU Used: ${double.parse(data["cpupercent_list"][0].toString()).toStringAsFixed(2)}% Memory Used: ${BytesToMBOnMemory(data["heapInuse"])}%'),
                      isThreeLine: true,
                      trailing: InkWell(
                          onTap: () {
                            loadAsync();
                            setState(() {});
                          },
                          child: Icon(Icons.refresh)),
                    ),
                    ClusterPieChart(
                      used: data["cpupercent_list"][0] as double,
                    )
                  ])),
            );
          }
        });
  }

  String BytesToMBOnMemory(int bytes) {
    return (bytes / pow(1024, 2)).toStringAsFixed(2);
  }
}

class ClusterPieChart extends StatefulWidget {
  const ClusterPieChart({super.key, required this.used});
  final double used;
  @override
  State<ClusterPieChart> createState() => PieChart2State();
}

class PieChart2State extends State<ClusterPieChart> {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1.3,
      child: Row(
        children: <Widget>[
          const SizedBox(
            height: 18,
          ),
          Expanded(
            child: AspectRatio(
              aspectRatio: 1,
              child: PieChart(
                PieChartData(
                  pieTouchData: PieTouchData(
                    touchCallback: (FlTouchEvent event, pieTouchResponse) {
                      setState(() {
                        if (!event.isInterestedForInteractions ||
                            pieTouchResponse == null ||
                            pieTouchResponse.touchedSection == null) {
                          touchedIndex = -1;
                          return;
                        }
                        touchedIndex = pieTouchResponse
                            .touchedSection!.touchedSectionIndex;
                      });
                    },
                  ),
                  borderData: FlBorderData(
                    show: false,
                  ),
                  sectionsSpace: 0,
                  centerSpaceRadius: 40,
                  sections: showingSections(widget.used),
                ),
              ),
            ),
          ),
          const Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Indicator(
                color: AppColors.contentColorBlue,
                text: 'CPU 利用率',
                isSquare: true,
              ),
            ],
          ),
          const SizedBox(
            width: 28,
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections(double used) {
    return List.generate(2, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = isTouched ? 25.0 : 16.0;
      final radius = isTouched ? 60.0 : 50.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 2)];
      switch (i) {
        case 0:
          return PieChartSectionData(
            color: AppColors.contentColorBlue,
            value: used,
            title: '${used.toStringAsFixed(2)}%',
            radius: radius,
            titleStyle: TextStyle(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
              color: AppColors.mainTextColor1,
              shadows: shadows,
            ),
          );
        case 1:
          return PieChartSectionData(
            color: const Color.fromARGB(255, 78, 78, 78),
            value: 100 - used,
            title: '${(100 - used).toStringAsFixed(2)}%',
            radius: radius,
            titleStyle: TextStyle(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
              color: AppColors.mainTextColor1,
              shadows: shadows,
            ),
          );
        default:
          throw Error();
      }
    });
  }
}

class AppColors {
  static const Color primary = contentColorCyan;
  static const Color menuBackground = Color(0xFF090912);
  static const Color itemsBackground = Color(0xFF1B2339);
  static const Color pageBackground = Color(0xFF282E45);
  static const Color mainTextColor1 = Colors.white;
  static const Color mainTextColor2 = Colors.white70;
  static const Color mainTextColor3 = Colors.white38;
  static const Color mainGridLineColor = Colors.white10;
  static const Color borderColor = Colors.white54;
  static const Color gridLinesColor = Color(0x11FFFFFF);

  static const Color contentColorBlack = Colors.black;
  static const Color contentColorWhite = Colors.white;
  static const Color contentColorBlue = Color(0xFF2196F3);
  static const Color contentColorYellow = Color(0xFFFFC300);
  static const Color contentColorOrange = Color(0xFFFF683B);
  static const Color contentColorGreen = Color(0xFF3BFF49);
  static const Color contentColorPurple = Color(0xFF6E1BFF);
  static const Color contentColorPink = Color(0xFFFF3AF2);
  static const Color contentColorRed = Color(0xFFE80054);
  static const Color contentColorCyan = Color(0xFF50E4FF);
}

class Indicator extends StatelessWidget {
  const Indicator({
    super.key,
    required this.color,
    required this.text,
    required this.isSquare,
    this.size = 16,
    this.textColor,
  });
  final Color color;
  final String text;
  final bool isSquare;
  final double size;
  final Color? textColor;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          width: size,
          height: size,
          decoration: BoxDecoration(
            shape: isSquare ? BoxShape.rectangle : BoxShape.circle,
            color: color,
          ),
        ),
        const SizedBox(
          width: 4,
        ),
        Text(
          text,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: textColor,
          ),
        )
      ],
    );
  }
}
